<template>
  <div class="container">
    <van-tabs swipeable v-model="activeIndex" :lazy-render="false" @change="changeChannel">
      <van-tab v-for="item in channels" :title="item.name" :key="item.id">
        <div class="scroll-wrapper" @scroll="remember($event)" ref="scroll-wrapper">
          <van-pull-refresh
            v-model="activeChannel.downLoading"
            @refresh="onRefresh"
            :success-text="successText"
          >
            <van-list
              v-model="activeChannel.upLoading"
              :finished="activeChannel.finished"
              finished-text="没有更多了"
              @load="onLoad"
            >
              <van-cell v-for="article in activeChannel.articles" :key="article.art_id.toString()">
                <div class="article_item">
                  <h3 class="van-ellipsis">{{article.title}}</h3>
                  <div class="img_box" v-if="article.cover.type===3">
                    <van-image lazy-load class="w33" fit="cover" :src="article.cover.images[0]" />
                    <van-image lazy-load class="w33" fit="cover" :src="article.cover.images[1]" />
                    <van-image lazy-load class="w33" fit="cover" :src="article.cover.images[2]" />
                  </div>
                  <div class="img_box" v-if="article.cover.type===1">
                    <van-image lazy-load class="w100" fit="cover" :src="article.cover.images[0]" />
                  </div>
                  <div class="info_box">
                    <span>{{article.aut_name}}</span>
                    <span>{{article.comm_count}}评论</span>
                    <span>{{article.pubdate|relTime}}</span>
                    <span class="close" v-if="auth.token" @click="showMoreAction(article.art_id)">
                      <van-icon name="cross"></van-icon>
                    </span>
                  </div>
                </div>
              </van-cell>
            </van-list>
          </van-pull-refresh>
        </div>
      </van-tab>
    </van-tabs>
    <span class="bar_btn">
      <van-icon name="wap-nav"></van-icon>
    </span>
    <more-action v-model="showMore" v-if="auth.token" :articleId="articleId.toString()" @on-del="delDislike"></more-action>
  </div>
</template>

<script>
import { getChannels } from '@/api/channel.js'
import { getArticles } from '@/api/article.js'
import { mapState } from 'vuex'
import MoreAction from './components/more-action'
export default {
  components: { MoreAction },

  name: 'home-index',
  data () {
    return {
      // downLoading: false,
      // upLoading: false,
      // // 是否全部加载完成
      // finished: false,
      // // 文章列表
      // articles: [],
      successText: null,
      channels: [],
      activeIndex: 0,
      showMore: false,
      articleId: ''
    }
  },
  created () {
    this.getChannels()
  },
  computed: {
    activeChannel () {
      return this.channels[this.activeIndex]
    },
    ...mapState(['auth'])
  },
  // =============监听到用户登录
  watch: {
    auth () {
      this.getChannels()
      this.onLoad()
    }
  },
  // =============================激活组件时调用】
  activated () {
    // =====在这里要操作dom元素
    if (this.$refs['scrollWrapper']) {
      const dom = this.$refs['scrollWrapper'][this.activeIndex]
      dom.scrollTop = this.activeChannel.scrollTop
    }
  },
  methods: {
    // ===========删除不喜欢文章
    delDislike () {
      const article = this.activeChannel.articles
      const index = article.findIndex(item =>
        item.art_id === this.articleId)
      article.splice(index, 1)
    },
    // =========打开举报的弹窗
    showMoreAction (articleId) {
      this.showMore = true
      this.articleId = articleId
    },
    // ===========记得滚动位置
    remember (e) {
      this.activeChannel.scrollTop = e.target.scrollTop
    },
    // ===================切换tab
    changeChannel () {
      if (this.activeChannel.articles.length) {
        this.nextTick(() => {
          const dom = this.$refs['scrollWrapper'][this.activeIndex]
          dom.scrollTop = this.activeChannel.scrollTop
        })
      } else {
        this.activeChannel.upLoading = true
        this.onLoad()
      }
    },
    // =====只用接口返回的数据不能完成需求，所以要用map往频道数组里添加一些数据
    // ===id,name,uploading.downloding.finnished,articles,timestamp都要加进去
    async getChannels () {
      const data = await getChannels()
      this.channels = data.channels.map(item => ({
        id: item.id,
        name: item.name,
        upLoading: false,
        downLoading: false,
        articles: [],
        timestamp: Date.now(),
        scrollTop: 0
      }))
      console.log(data)
    },
    async onRefresh () {
      await this.$sleep()

      this.activeChannel.timestamp = Date.now()
      const data = await getArticles(this.activeChannel.id, this.activeChannel.timestamp)
      this.activeChannel.downLoading = false
      if (data.results.length) {
        this.activeChannel.articles = data.results
        this.successText = '刷新成功'
        this.activeChannel.timestamp = data.pre_timestamp
        this.activeChannel.finished = false
        this.onLoad()
      } else {
        this.successText = '暂无更新'
      }
    },
    async onLoad () {
      // 获取数据 渲染列表
      // window.setTimeout(() => {
      //   // 模拟获取了数据
      //   const data = [];
      //   for (
      //     let i = this.articles.length + 1;
      //     i <= this.articles.length + 10;
      //     i++
      //   ) {
      //     data.push(i);
      //   }
      //   // 追加到 articles 中
      //   this.articles.push(...data);
      //   // 把加载中状态  加载结束
      //   this.upLoading = false;
      //   // 假设所有的数据 50 条
      //   if (this.articles.length >= 50) {
      //     this.finished = true;
      //   }
      // }, 1000);
      // 在这里利用了上拉加载的功能实现当前频道的数据获取也就是文章获取
      await this.$sleep()

      const data = await getArticles(
        this.activeChannel.id,
        this.activeChannel.timestamp
      )
      // console.log(data);
      this.activeChannel.articles.push(...data.results)
      // console.log(this.activeChannel.articles)
      this.activeChannel.upLoading = false
      if (!data.pre_timestamp) {
        this.activeChannel.finished = true
      } else {
        this.activeChannel.timestamp = data.pre_timestamp
      }
    }
  }
}
</script>

<style scoped lang='less'>
// deep 深度
// 组件style标签  scoped属性：让样式在当前组件下生效
// 如果你想 修改子组件的样式  使用 /deep/ 深度修改
.van-tabs {
  height: 100%;
  display: flex;
  flex-direction: column;
  /deep/ .van-tabs__wrap {
    height: 36px;
    padding-right: 36px;
    .van-tab {
      line-height: 36px;
    }
    .van-tabs__line {
      background-color: #3296fa;
      height: 2px;
    }
  }
  /deep/ .van-tabs__content {
    flex: 1;
    overflow: hidden;
  }
  /deep/ .van-tab__pane {
    height: 100%;
    .scroll-wrapper {
      height: 100%;
      overflow-y: auto;
    }
  }
}
// 按钮样式
.bar_btn {
  width: 36px;
  height: 35px;
  position: absolute;
  top: 0;
  right: 0;
  &::before {
    content: "";
    width: 100%;
    height: 100%;
    position: absolute;
    z-index: 999;
    box-shadow: 0 0 10px #999;
    transform: scale(1, 0.6);
  }
  .van-icon-wap-nav {
    width: 100%;
    height: 100%;
    background: #fff;
    text-align: center;
    line-height: 35px;
    position: relative;
    z-index: 1000;
    &::before {
      font-size: 20px;
    }
  }
}
// 文章内容
.article_item {
  h3 {
    font-weight: normal;
    line-height: 2;
  }
  .img_box {
    display: flex;
    justify-content: space-between;
    .w33 {
      width: 33%;
      height: 90px;
    }
    .w100 {
      width: 100%;
      height: 180px;
    }
  }
  .info_box {
    color: #999;
    line-height: 2;
    position: relative;
    font-size: 12px;
    span {
      padding-right: 10px;
      &.close {
        border: 1px solid #ddd;
        border-radius: 2px;
        line-height: 15px;
        height: 12px;
        width: 16px;
        text-align: center;
        padding-right: 0;
        font-size: 8px;
        position: absolute;
        right: 0;
        top: 7px;
      }
    }
  }
}
</style>
